const fs = require('fs')
const path = require('path')

function getFileContent(fileName, callback) {
  const fullFileName = path.resolve(__dirname, 'static', fileName)
  fs.readFile(fullFileName, (err, data) => {
    if (err) {
      console.log(err)
      return
    }
    callback(JSON.parse(data))
  })
}

// 测试 callback-hell
// getFileContent('a.json', aData => {
//   console.log('a data', aData)
//   getFileContent(aData.next, bData => {
//     console.log('b data', bData)
//     getFileContent(bData.next, cData => {
//       console.log('c data', cData)
//     })
//   })
// })

// 用 promise 实现
function getFileContentByPromise(fileName) {
  const promise = new Promise((resolve, reject) => {
    const fullFileName = path.resolve(__dirname, 'static', fileName)
    fs.readFile(fullFileName, (err, data) => {
      if (err) {
        reject(err)
        return
      }
      resolve(JSON.parse(data.toString()))
    })
  })
  return promise
}

getFileContentByPromise('a.json')
  .then(aData => {
    console.log('a data', aData)
    return getFileContentByPromise(aData.next)
  })
  .then(bData => {
    console.log('b data', bData)
    return getFileContentByPromise(bData.next)
  })
  .then(cData => {
    console.log('c data', cData)
  })
